package com.ken.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class QRUtil {
    public static String createQR(String content) throws Exception {
        Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 使用File.createTempFile()创建临时文件
        Path tempFilePath = Files.createTempFile("ken-", ".jpg");
        File tempFile = tempFilePath.toFile();
        // 生成二维码矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
        // 将矩阵转换为图像并保存到临时文件
        MatrixToImageWriter.writeToPath(bitMatrix, "JPG", tempFilePath);
        UUID uuid = UUID.randomUUID();
        String url = OssUtil.upload(tempFile, uuid.toString()+".jpg");
        return url;
    }
}
